//
//  PhotoBrowserAnimator.swift
//  SinaWeibo
//
//  Created by 小果 on 16/3/1.
//  Copyright © 2016年 小果. All rights reserved.
//

import UIKit
import SDWebImage

/// 提供从控制器向图片浏览器的modal的转成动画的对象
class PhotoBrowserAnimator: NSObject,UIViewControllerTransitioningDelegate {
    // 是否展现的标记
    var isPresented = false
    // 起始位置和目标位置
    var fromRect = CGRectZero
    var toRect = CGRectZero
    // 图像视图的URL
    var url: NSURL?
    // 动画播放的图像视图
    lazy var imageView: XGProgressIconView = {
        let iv = XGProgressIconView()
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        iv.clipsToBounds = true
        
        return iv
    }()
    // 首页控制器中的配图视图
    weak var picView: StatusPictureView?
    
    ///  主被动画的参数
    ///  - parameter picView: cell中的配图视图
    ///  - parameter fromRect: fromRect
    ///  - parameter toRect:   toRect
    ///  - parameter url:      url
    func prepareAnimation(picView: StatusPictureView, fromRect: CGRect, toRect: CGRect, url: NSURL) {
        self.picView = picView
        self.fromRect = fromRect
        self.toRect = toRect
        self.url = url
    }
    
    // 返回提供展现转场动画的对象
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        isPresented = true
        
        return self
    }
    // 返回提供 解除 转场动画的对象
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        isPresented = false
        
        return self
    }
}

// MARK: - 转场动画的协议
extension PhotoBrowserAnimator: UIViewControllerAnimatedTransitioning {
    // 返回转场动画的时长
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.5
    }
    // 实现转场动画的效果（该动画一旦实现，必须完成动画效果）
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
        let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
        printLog(fromVC)
        printLog(toVC)
        
        isPresented ? presentAnimation(transitionContext) : dismissAnimation(transitionContext)
    }
    
    // 实现解除转场动画
    private func dismissAnimation(transitionContext: UIViewControllerContextTransitioning) {
        
        let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! PhotoBrowserController
        // 通过控制器来胡获得内部的ImageView
        let imageView = fromVC.currentImageView
        let indexPath = fromVC.curretnImageIndex
        
        // 拿到被展现的视图
        let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
        // 直接将fromeView从容器视图删除
        fromView.removeFromSuperview()
        
        // 将图像视图添加到容器视图中
        transitionContext.containerView()?.addSubview(imageView)
        // 设置imageView的位置
        imageView.center = fromView.center
        
        // 叠加 imageView 的形变参数 － 将 fromVC 的 view 的缩放形变叠加到 imageView 上
        let scale = fromVC.view.transform.a
        imageView.transform = CGAffineTransformScale(imageView.transform, scale, scale)
        imageView.alpha = scale

        UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
            // 单纯修改最外侧的 view 的 frame 无法达到预期的效果
            imageView.frame = self.picView!.screenRect(indexPath)
            imageView.alpha = 1.0
            
            }, completion: { (_) -> Void in
                
                // 将试图从容器视图中移除
                imageView.removeFromSuperview()
                // 动画完成
                transitionContext.completeTransition(true)
        })
        
    }
    
    // 实现modal 展现动画
    private func presentAnimation(transitionContext: UIViewControllerContextTransitioning) {
        // 1、将imageView添加到容器视图
        transitionContext.containerView()?.addSubview(imageView)
        imageView.frame = fromRect
        
        // 2、使用SDWebImage异步加载图像
    imageView.sd_setImageWithURL(url, placeholderImage: nil, options: [SDWebImageOptions.RetryFailed], progress: { (current, total) -> Void in
        
        // 设置进度(计算下载进度)
        dispatch_async(dispatch_get_main_queue()) {
            self.imageView.progress = CGFloat(current) / CGFloat(total)
        }
        
        }) { (_, error, _, _) -> Void in
            // 判断是否有错误
            if error != nil {
                printLog(error, logError: true)
                
                // 声明动画结束(参数为false，容器视图不会添加，转场失败)
                transitionContext.completeTransition(false)
                
                return
            }
                
        // 3、图像下载完成后执行动画
        UIView.animateWithDuration(self.transitionDuration(transitionContext), animations: { () -> Void in
            self.imageView.frame = self.toRect
            
            }, completion: { (_) -> Void in
                // 将目标视图添加到容器视图
                // 展现动画
                let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
                transitionContext.containerView()?.addSubview(toView)
                // 将imageView从界面上删除
                self.imageView.removeFromSuperview()
                // 声明动画结束
                transitionContext.completeTransition(true)

        })
        
        
        }
        
    }
}
